//
//  LoginV2ViewModel.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/11/8.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "LoginV2ViewModel.h"

@interface LoginV2ViewModel ()

/// 验证码按钮点击执行的命令
@property (nonatomic, readwrite, strong) RACCommand *verCodeCommand;
/// 登录按钮点击执行的命令
@property (nonatomic, readwrite, strong) RACCommand *loginCommand;
/// 微信按钮点击执行的命令
@property (nonatomic, readwrite, strong) RACCommand *wxCommand;

@end

@implementation LoginV2ViewModel

#pragma mark - Ovrride
- (void)initialize
{
    [super initialize];
    
    @weakify(self)
    
    _type = 0;
    /// 登录命令
    self.loginCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        // 这里手机号以及验证码在控制器那里也可以在视图控制器筛选，但同时也可以在viewModel中处理
        // 最好的写法:button.rac_command = viewmodel.loginCommand...把位数判断移到这里
        
        switch (self.type)
        {
            case 0: //账号密码
            {
                if ([NSString mh_isBlankString:self.strPwdLoginPhone] || [NSString mh_isBlankString:self.strPwd]/* || self.strPwd.length < 6*/)
                {
                    return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:@"请输入正确的账号和密码"}]];
                }
                
                @weakify(self);
                return [self requestLoginSignal];
            }
                break;
                
            case 1: //手机验证码
            {
                if (![NSString mh_isValidMobile:self.strVercodeLoginPhone]) {
                    
                    return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:@"请输入正确的手机号码"}]];
                }
                if (![NSString mh_isPureDigitCharacters:self.strVercode] || self.strVercode.length !=6)
                {
                    return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:@"验证码错误"}]];
                }
                
                @weakify(self);
                return [self requestLoginSignal];
            }
                break;
                
            default:
                break;
        }
        
        // Type 赋值有误
        return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:@"登录Type赋值有误"}]];
    }];
    
    /// 微信登陆命令
    self.wxCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        
        SendAuthReq* req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo";
        req.state = @"EnvironmentalProtaction";
        [WXApi sendReq:req];
        
        /// 微信返回信息
        return [[[[[[NSNotificationCenter defaultCenter] rac_addObserverForName:Notify_WXResp object:nil] flattenMap:^RACStream *(id value) {
            @strongify(self)
            
            NSNotification* notify = value;
            
            if ([notify.object isKindOfClass:[NSDictionary class]])
            {
                NSDictionary* dic = notify.object;
                
                return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:dic[@"ErrorTip"]}]];
            }
            
            return [self requestWXAccessTokenAndOpenIdByCode:notify.object];
        }] flattenMap:^RACStream *(id value) {
            @strongify(self)
            
            NSDictionary *dic = value;
            
            NSString* accessToken = [dic valueForKey:@"access_token"];
            NSString* openID = [dic valueForKey:@"openid"];
            
            return [self requestUserInfoByToken:accessToken andOpenid:openID];
        }] flattenMap:^RACStream *(id value) {
            @strongify(self)
            
            NSDictionary *dic = (NSDictionary *)value;
            
            return [self requestThirdLoginSignal:dic];
        }] flattenMap:^RACStream *(id value) {
            @strongify(self);
            
            NSDictionary* info = value;
            
            UserInfoData* data = [UserInfoData modelWithJSON:info];
            
            return [self requestUserInfoSignal:data.userID];
        }];
    }];
    
    self.verCodeCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        
        DataManager* dm = [DataManager sharedDataManager];
        
        if (dm.phoneVCodeCaler.verCodeTime > 0)
        {
            return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:[NSString stringWithFormat:@"请%d秒后再试", dm.phoneVCodeCaler.verCodeTime]}]];
        }
        
        if (![NSString mh_isValidMobile:self.strVercodeLoginPhone]) {
            
            return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:@"请输入正确的手机号码"}]];
        }
        
        return [self requestVercodeSignal];
    }];
}

#pragma mark - Request
- (RACSignal*)requestVercodeSignal
{
    @weakify(self)
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        @strongify(self)
        
        DataManager* dm = [DataManager sharedDataManager];
        [dm.phoneVCodeCaler waitGetCode];
        
        NSDictionary* postData = interface_param_sendMessage(self.strVercodeLoginPhone);
        
        @weakify(self)
        /// 发起请求
        [[AFNetWorkUtils racPOSTWthURL:url_interface_sendMessage params:postData] subscribeNext:^(id x) {
            //成功返回(result class is NSDictionary)
            
            @strongify(self);
            
            self.contrastVerCode = x[@"code"];
            
            [subscriber sendNext:x[SUCommandSysMessageKey]];
            [subscriber sendCompleted];
        } error:^(NSError *error) {
            //错误处理
            
            NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"请求验证码失败，请稍后再试";
            [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
            [subscriber sendCompleted];
        }];
        
        return nil;
    }];
}

- (RACSignal*)requestThirdLoginSignal:(NSDictionary*)dic
{
    NSString* unionId = dic[@"unionid"];
    NSString* nickname = dic[@"nickname"];
    NSString* header = dic[@"headimgurl"];
    NSString* sex = HCStrFormat(@"%d", (int)([dic[@"sex"] integerValue] - 1));
    
    NSDictionary* postData = interface_param_wechatLogin(unionId, nickname, header);
    
    @weakify(self)
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        @strongify(self)
        
        @weakify(self)
        /// 发起请求
        [[AFNetWorkUtils racPOSTWthURL:url_interface_wechatLogin params:postData] subscribeNext:^(id x) {
            //成功返回(result class is NSDictionary)
            
            @strongify(self);
            UserInfoData* data = [UserInfoData modelWithJSON:x];
            
            UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
//            [um saveUserData:data];
            //            [userManager loginSave:@"A7DAC6D2B408E38392F6614C6B3CAE7F"];
            //            [userManager loginSave:hdLogin.token];
            
            [um updateUserToken:data.userID];
            
            [subscriber sendNext:x];
            [subscriber sendCompleted];
        } error:^(NSError *error) {
            //错误处理
            
            NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"登录失败";
            [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
            [subscriber sendCompleted];
        }];
        
        return nil;
    }];
}

- (RACSignal*)requestLoginSignal
{
    @weakify(self)
    
    NSString* strReqMobile = self.type == 0 ? self.strPwdLoginPhone : self.strVercodeLoginPhone;
    NSString* strPwd = self.type == 0 ? self.strPwd : @"";
    NSString* strVerCode = self.type == 0 ? @"" : self.strVercode;
    NSString* strType = self.type == 0 ? @"1" : @"2";
    
    NSDictionary* postData = interface_param_login(strReqMobile, strPwd, strVerCode, strType);
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        @strongify(self)
        
        @weakify(self)
        /// 发起请求
        [[AFNetWorkUtils racPOSTWthURL:url_interface_login params:postData] subscribeNext:^(id x)
         {
             @strongify(self)
             
             UserInfoData* data = [UserInfoData modelWithJSON:x];
             
             UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
//             [um saveUserData:data];
             
             [um updateUserToken:data.userID];
             
             [subscriber sendNext:x[SUCommandSysMessageKey]];
             [subscriber sendCompleted];
         }   error:^(NSError *error) {
             //错误处理
             
             NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"登录失败";
             [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
             [subscriber sendCompleted];
         }];
        
        return nil;
    }];
}

- (RACSignal*)requestUserInfoSignal:(NSString*)userID
{
    @weakify(self)
    
    NSDictionary* postData = interface_param_userInfo(userID);
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        @strongify(self)
        
        @weakify(self)
        /// 发起请求
        [[AFNetWorkUtils racPOSTWthURL:url_interface_userInfo params:postData] subscribeNext:^(id x)
         {
             @strongify(self)
             
             UserInfoData* data = [UserInfoData modelWithJSON:x];
             
             [subscriber sendNext:data];
             [subscriber sendCompleted];
         }   error:^(NSError *error) {
             //错误处理
             
             NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"登录失败";
             [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
             [subscriber sendCompleted];
         }];
        
        return nil;
    }];
}

#pragma mark 微信登录回调。
- (RACSignal *)requestWXAccessTokenAndOpenIdByCode:(NSString*)code
{
    NSLog(@"code %@",code);
    
    NSString* strUrl = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",APPID_WX,APPSERCRET_WX,code];
    
    return [AFNetWorkUtils racGETWthURL:strUrl];
    
    //    [[AFNetWorkUtils racGETWthURL:strUrl] subscribeNext:^(id x)
    //    {
    //        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:x options:NSJSONReadingMutableContainers error:nil];
    //        NSLog(@"dic %@",dic);
    //
    //        /*
    //         access_token   接口调用凭证
    //         expires_in access_token接口调用凭证超时时间，单位（秒）
    //         refresh_token  用户刷新access_token
    //         openid 授权用户唯一标识
    //         scope  用户授权的作用域，使用逗号（,）分隔
    //         unionid     当且仅当该移动应用已获得该用户的userinfo授权时，才会出现该字段
    //         */
    //        NSString* accessToken=[dic valueForKey:@"access_token"];
    //        NSString* openID=[dic valueForKey:@"openid"];
    //
    //
    //
    //    } error:^(NSError *error) {
    //
    //    }];
    //
    //
    //
    //
    //
    //
    //
    //    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];//响应
    //    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json",@"text/plain", nil nil];
    //    //通过 appid  secret 认证code . 来发送获取 access_token的请求
    //    [manager GET:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",URL_APPID,URL_SECRET,code] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    //
    //    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {  //获得access_token，然后根据access_token获取用户信息请求。
    //
    //        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
    //        NSLog(@"dic %@",dic);
    //
    //        /*
    //         access_token   接口调用凭证
    //         expires_in access_token接口调用凭证超时时间，单位（秒）
    //         refresh_token  用户刷新access_token
    //         openid 授权用户唯一标识
    //         scope  用户授权的作用域，使用逗号（,）分隔
    //         unionid     当且仅当该移动应用已获得该用户的userinfo授权时，才会出现该字段
    //         */
    //        NSString* accessToken=[dic valueForKey:@"access_token"];
    //        NSString* openID=[dic valueForKey:@"openid"];
    //        [weakSelf requestUserInfoByToken:accessToken andOpenid:openID];
    //    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    //        NSLog(@"error %@",error.localizedFailureReason);
    //    }];
    
}

- (RACSignal *)requestUserInfoByToken:(NSString *)token andOpenid:(NSString *)openID
{
    NSString* strUrl = [NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openID];
    
    return [AFNetWorkUtils racGETWthURL:strUrl];
    
    //    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    //    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //    [manager GET:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",token,openID] parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
    //
    //    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    //        NSDictionary *dic = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
    //        NSLog(@"dic  ==== %@",dic);
    //
    //    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    //        NSLog(@"error %ld",(long)error.code);
    //    }];
}

@end
